package com.ypan.monitor.osutils;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class Sensors implements SensorEventListener {
	private static Sensors instance = null;
	private List<Sensor> sensors = new ArrayList<Sensor>();
	private ArrayList<SensorListItem> list = new ArrayList<SensorListItem>();
	private SensorListener sListener = null;

	private Sensors() {

	}

	public static Sensors getInstance() {
		synchronized (Sensors.class) {
			if (instance == null) {
				instance = new Sensors();
			}
			return instance;
		}
	}

	public void initSensors(Context ctx) {
		SensorManager sm = (SensorManager) ctx
				.getSystemService(Context.SENSOR_SERVICE);
		sensors = sm.getSensorList(Sensor.TYPE_ALL);
		list.clear();
		for (Sensor ss : sensors) {
			list.add(new SensorListItem(ss));
		}
	}

	public void onResume(Context ctx) {
		SensorManager sm = (SensorManager) ctx
				.getSystemService(Context.SENSOR_SERVICE);
		for (Sensor ss : sensors) {
			sm.registerListener(this, ss, SensorManager.SENSOR_DELAY_UI);
		}
	}

	public void onPause(Context ctx) {
		SensorManager sm = (SensorManager) ctx
				.getSystemService(Context.SENSOR_SERVICE);
		for (Sensor ss : sensors) {
			sm.unregisterListener(this, ss);
		}
	}

	public ArrayList<SensorListItem> getItems() {
		return list;
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		String name = event.sensor.getName();
		float[] v = event.values;
		update(name, v);
		if (sListener != null) {
			sListener.onSensorChanged();
		}
	}

	private void update(String name, float[] v) {
		for (SensorListItem item : list) {
			if (item.name.equals(name)) {
				item.values[0] = v[0];
				item.values[1] = v[1];
				item.values[2] = v[2];
				item.status = "Good";
				break;
			}
		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {

	}

	public void setSensorListener(SensorListener listener) {
		sListener = listener;
	}

	public interface SensorListener {
		public void onSensorChanged();
	}
}
